package org.torproject.android;

import java.util.ArrayList;
import java.util.List;

import android.os.Parcel;
import android.os.Parcelable;

public class Circuit implements Parcelable {
	
	public Circuit(String input) throws InvalidCircuitException {
		id = "";
		path = "";
		status = "";
		
		String[] args = input.split(" ");
		if(args.length < 3) {
			throw new InvalidCircuitException("Invalid input for the circuit: " + input);
		}
		
		id = args[0];
		
		status = args[1];
		if(status.equalsIgnoreCase("BUILT")) {
			status = "OPEN";
		}

		String[] pathRaw = args[2].split(",");
		for(String pathRawElement : pathRaw) {
			String tokens[] = pathRawElement.split("=");
			if(tokens.length < 2) {
				throw new InvalidCircuitException("Invalid input for the circuit: " + input);
			}
			fingerPrints.add(tokens[0]);
			if(path.length() == 0) {
				path = tokens[1];
			}
			else {
				path += "," + tokens[1];
			}
		}
	}
	
	public String toString() {
		return status + ": " + path;
	}
	
	public String id;
	public String status;
	public String path;
	public List<String> fingerPrints = new ArrayList<String>();
	public List<RouterDescriptor> routerDescriptors = new ArrayList<RouterDescriptor>();
	 
	private Circuit(Parcel p) {
		id = p.readString();
		status = p.readString();
		path = p.readString();
		p.readList(fingerPrints, null);
		p.readList(routerDescriptors, RouterDescriptor.class.getClassLoader());
	}

	public static final Parcelable.Creator<Circuit> CREATOR = new Parcelable.Creator<Circuit>() {
    			public Circuit createFromParcel(Parcel in) {
    				return new Circuit(in);
    			}

    			public Circuit[] newArray(int size) {
    				return new Circuit[size];
    			}
    };


	public int describeContents() {
		// TODO Auto-generated method stub
		return 0;
	}
	
	public void writeToParcel(Parcel arg0, int arg1) {
		arg0.writeString(id);
		arg0.writeString(status);
		arg0.writeString(path);
		arg0.writeList(fingerPrints);
		arg0.writeList(routerDescriptors);
	}
	
}
